package com.yunshan.mp;

import com.yunshan.common.annotation.Log;
import com.yunshan.common.annotation.RepeatSubmit;
import com.yunshan.common.core.controller.BaseController;
import com.yunshan.common.core.domain.AjaxResult;
import com.yunshan.common.enums.BusinessType;
import com.yunshan.common.utils.DateUtils;
import com.yunshan.common.utils.StringUtil;
import com.yunshan.common.utils.StringUtils;
import com.yunshan.common.utils.UserUtils;
import com.yunshan.member.domain.MemberSubCardInfo;
import com.yunshan.member.domain.MemberUserInfo;
import com.yunshan.member.service.IMemberSubCardInfoService;
import com.yunshan.member.service.IMemberUserInfoService;
import com.yunshan.order.domain.OrderConsumeRecord;
import com.yunshan.order.domain.OrderUniVo;
import com.yunshan.order.service.IOrderConsumeRecordService;
import com.yunshan.wechat.domain.WechatUserInfo;
import com.yunshan.wechat.service.IWechatUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 副卡管理Controller
 *
 * @author yunshan
 * @date 2025-04-08
 */
@Api(tags = "副卡管理")
@RestController
@RequestMapping("/wx/sub")
public class MpSubController extends BaseController {

    @Autowired
    private IMemberSubCardInfoService memberSubCardInfoService;
    @Autowired
    private IWechatUserInfoService wechatUserInfoService;
    @Autowired
    private IMemberUserInfoService memberUserInfoService;
    @Autowired
    private IOrderConsumeRecordService orderConsumeRecordService;

    /**
     * 新增副卡
     */
    @ApiOperation("新增副卡")
    @PostMapping
    public AjaxResult add(@RequestBody MemberSubCardInfo memberSubCardInfo)
    {
        Long userId = UserUtils.getUserId();
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
        if (wechatUserInfo.getType() != 1){
            return error("非主卡用户不允许创建副卡");
        }

        MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(userId);
        if (memberUserInfo == null || "2".equals(memberUserInfo.getMemberType()) || "4".equals(memberUserInfo.getMemberType())){
            return error("仅支持业主会籍和公司会籍类型创建副卡");
        }

        MemberUserInfo memberVerify = memberUserInfoService.selectMemberUserInfoByPhone(memberSubCardInfo.getPhone());
        if (memberVerify != null && !"4".equals(memberVerify.getMemberType())){
            return error("此手机号已是主卡用户，不可绑定副卡");
        }

        MemberSubCardInfo subCardInfo = memberSubCardInfoService.selectUserInfoByLoginPhone(memberSubCardInfo.getPhone());
        if (subCardInfo != null && subCardInfo.getStatus() != 3 && subCardInfo.getStatus() != 2){
            return error("此手机号已是副卡用户，不可再绑定副卡");
        }

        memberSubCardInfo.setMemberId(memberUserInfo.getId());
        memberSubCardInfo.setMemberName(memberUserInfo.getName());
        memberSubCardInfo.setLoginPhone(memberSubCardInfo.getPhone());

        //业主会籍
        if ("1".equals(memberUserInfo.getMemberType())){
            memberSubCardInfo.setStatus(1);
            memberSubCardInfo.setIssueTime(DateUtils.getNowDate());

            //查询是否存在小程序用户，存在则绑定并删除临时会籍
            WechatUserInfo subUserInfo = wechatUserInfoService.selectUserInfoByLoginPhone(memberSubCardInfo.getPhone());
            if (subUserInfo != null) {
                memberSubCardInfo.setUserId(subUserInfo.getId());

                //删除临时会籍
                MemberUserInfo preUserInfo = memberUserInfoService.selectUserInfoByUserId(subUserInfo.getId());
                if (preUserInfo != null) {
                    memberUserInfoService.deleteMemberUserInfoById(preUserInfo.getId());
                }

                //更新用户类型
                subUserInfo.setName(memberSubCardInfo.getName());
                subUserInfo.setType(2);
                wechatUserInfoService.updateWechatUserInfo(subUserInfo);
            }
        }

        return toAjax(memberSubCardInfoService.insertMemberSubCardInfo(memberSubCardInfo));
    }


    /**
     * 副卡查询
     */
    @ApiOperation("副卡查询")
    @GetMapping
    public AjaxResult get()
    {
        Long userId = UserUtils.getUserId();
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
        //判断是否主卡
        if (wechatUserInfo.getType() != 1){
            return success();
        }

        MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(userId);
        MemberSubCardInfo memberSubCardInfo = new MemberSubCardInfo();
        memberSubCardInfo.setMemberId(memberUserInfo.getId());
        List<MemberSubCardInfo> memberSubCardInfos = memberSubCardInfoService.selectMemberSubCardStatusList(memberSubCardInfo);

        if (memberSubCardInfos.size() > 0) {

            for (MemberSubCardInfo subCardInfo : memberSubCardInfos) {
                //手机号加密
                subCardInfo.setPhone(StringUtil.encryptPhoneNumber(subCardInfo.getPhone()));

                //查询最近一次消费订单
                OrderConsumeRecord orderConsumeRecord = new OrderConsumeRecord();
                orderConsumeRecord.setMemberId(subCardInfo.getId());
                orderConsumeRecord.setCardType(2);
                List<OrderUniVo> orderUniVos = orderConsumeRecordService.selectOrderUniList(subCardInfo.getId(), 2);
                if (orderUniVos.size() > 0) {
                    subCardInfo.setOrderConsumeRecord(orderUniVos.get(0));
                }
            }
        }

        return success(memberSubCardInfos);

    }

    /**
     * 副卡详情
     */
    @ApiOperation("副卡详情")
    @GetMapping("getInfo")
    public AjaxResult getInfo(
            @ApiParam(name = "id", value = "副卡id", required = true)
            @RequestParam Long id)
    {
        Long userId = UserUtils.getUserId();
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
        //判断是否主卡
        if (wechatUserInfo.getType() != 1){
            return success();
        }

        MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectMemberSubCardInfoById(id);

        if (memberSubCardInfo != null){
            //手机号加密
            memberSubCardInfo.setPhone(StringUtil.encryptPhoneNumber(memberSubCardInfo.getPhone()));

            //查询消费订单
            memberSubCardInfo.setMemberUserInfo(null);
            OrderConsumeRecord orderConsumeRecord = new OrderConsumeRecord();
            orderConsumeRecord.setMemberId(memberSubCardInfo.getId());
            orderConsumeRecord.setCardType(2);
            List<OrderUniVo> orderUniVos = orderConsumeRecordService.selectOrderUniSubList(memberSubCardInfo.getId(), 2);
            if (orderUniVos.size() > 0) {
                memberSubCardInfo.setOrderConsumeRecords(orderUniVos);
            }
        }

        return success(memberSubCardInfo);

    }


    /**
     * 副卡销卡
     */
    @ApiOperation("副卡销卡")
    @RepeatSubmit
    @PostMapping("cancelCard")
    public AjaxResult cancelCard(
            @RequestBody Map<String,Long> map) {
        try {
            Long id = map.get("id");

            Long userId = UserUtils.getUserId();
            if (userId == null) {
                return error("用户登录异常");
            }
            WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(userId);
            if (wechatUserInfo == null) {
                return error("用户信息异常");
            }

            MemberSubCardInfo memberSubCardInfo = memberSubCardInfoService.selectMemberSubCardInfoById(id);
            if (memberSubCardInfo != null && memberSubCardInfo.getStatus() != 3 && memberSubCardInfo.getStatus() != 2) {
                //如果有小程序用户则删除
                if (memberSubCardInfo.getUserId() != null){
                    wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(memberSubCardInfo.getUserId());
                    wechatUserInfoService.deleteWechatUserInfoById(wechatUserInfo.getId());
                    memberSubCardInfo = new MemberSubCardInfo();
                }
                memberSubCardInfo.setId(id);
                memberSubCardInfo.setStatus(3);
                return success(memberSubCardInfoService.updateMemberSubCardInfo(memberSubCardInfo));
            }

            return error("请检查副卡状态或稍后重试");
        }catch (Exception e){
            error(e.getMessage());
            return error("请检查副卡状态或稍后重试");
        }
    }


    /**
     * 副卡查询
     */
    @ApiOperation("历史记录")
    @GetMapping("records")
    public AjaxResult records()
    {
        WechatUserInfo wechatUserInfo = wechatUserInfoService.selectWechatUserInfoById(UserUtils.getUserId());
        //判断是否主卡
        if (wechatUserInfo.getType() != 1){
            return success();
        }

        MemberUserInfo memberUserInfo = memberUserInfoService.selectUserInfoByUserId(UserUtils.getUserId());
        MemberSubCardInfo memberSubCardInfo = new MemberSubCardInfo();
        memberSubCardInfo.setMemberId(memberUserInfo.getId());

        return success(memberSubCardInfoService.selectMemberSubCardInfoRecords(memberSubCardInfo));

    }

}
